<?php

/**
 * 后台公共文件 
 * @file   Common.php  
 * @date   2016-8-24 18:28:34 
 * @author Zhenxun Du<5552123@qq.com>  
 * @version    SVN:$Id:$ 
 */

namespace app\admin\controller;

use app\admin\model\JsAdminGroup;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Controller;
use think\Config;
use \OSS\OssClient;
use app\admin\model\JsAdminMenu;
use app\admin\model\JsAdminLog;
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use think\Db;


class Common extends Controller {

    protected $user_id;
    protected $user_name;
    protected $user_type;
    protected $company_id;
    protected $company_name;
    protected $company_type;
    protected $inData,$outData;
    protected $pernum = 8;
    protected $db_app;

    public function __construct(\think\Request $request = null) {

        parent::__construct($request);
        // 加载配置文件
        Config::load(APP_PATH.'admin/config.php');

        if (!session('user_id')) {
            $this->redirect('login/index');
        }

        $this->db_app = Db::connect('database_app');

        $this->user_id = session('user_id');
        $this->user_name = session('user_name');
        $this->user_type = session('user_type');
        $this->company_name = session('company_name');
        $this->company_type = session('company_type');
        $this->company_id = session('company_type');

        $leftMenu = array();

        switch ($this->user_type) {
            case 1:
                $leftMenu = config('ceo_menu');
                // 根据公司类型处理目录显示
                if ($this->company_type == 1) { // 省
                    // 省公司
                } elseif ($this->company_type == 2) { // 市
                    // 市公司
                    unset($leftMenu['cityCompany']);
                } elseif ($this->company_type == 3) { // 县
                    // 县公司
                    unset($leftMenu['cityCompany']);
                    unset($leftMenu['countyCompany']);
                } elseif ($this->company_type == 4) { // 惠民店
                    unset($leftMenu['cityCompany']);
                    unset($leftMenu['countyCompany']);
                    unset($leftMenu['townsCompany']);
                }


                break;
            case 2:
                $leftMenu = config('finance_menu');
                break;
            case 3:
                $leftMenu = config('official_menu');
                break;
        }


        $controllerName = strtolower(request()->controller());
        $actionName = strtolower(request()->action());

//        dump($leftMenu);
//        dump($controllerName);
//        dump($actionName);
        switch ($controllerName) {
            case 'index':
                $leftMenu['index']['active'] = 1;
                break;

            case 'stockholder':
                $leftMenu['stockholder']['active'] = 1;
                break;

            case 'auth':
                $leftMenu['auth']['active'] = 1;
                break;

            case 'income':
                $leftMenu['income']['active'] = 1;
                break;

            case 'profit':
                switch ($actionName) {
                    case 'index':
                    case 'stockmoneyallotlist':
                        $leftMenu['profit']['active'] = 1;
                        break;

                    case 'checklist':
                        $leftMenu['profitCheckList']['active'] = 1;
                        break;
                    default:
                        $leftMenu['profit']['active'] = 1;
                        break;
                }

                break;

            case 'purchase':
                switch ($actionName) {
                    case 'checklist':
                    case 'check':
                        $leftMenu['purchaseCheckList']['active'] = 1;
                        break;

                    case 'applylist':
                    case 'apply':
                        $leftMenu['purchaseApplyList']['active'] = 1;
                        break;
                    default:
                }

                break;

            case 'citycompany':
                $leftMenu['cityCompany']['active'] = 1;
                break;

            case 'countycompany':
                $leftMenu['countyCompany']['active'] = 1;
                break;

            case 'townscompany':
                $leftMenu['townsCompany']['active'] = 1;
                break;
        }



        $this->assign('leftMenu',$leftMenu);

        $this->assign('companyName',$this->company_name);

        //记录日志
        $this->_addLog();
        $this->outData = array('data'=>'','code'=>'','message'=>'');//输出参数
    }


    /**
     * 记录日志
     */
    private function _addLog() {

        $data = array();
        $data['querystring'] = request()->query()?'?'.request()->query():'';
        $data['m'] = request()->module();
        $data['c'] = request()->controller();
        $data['a'] = request()->action();
        $data['userid'] = $this->user_id;
        $data['username'] = $this->user_name;
        $data['ip'] = ip2long(request()->ip());
	    $data['time'] = time();
        $arr = array('Index/index','Log/index','Menu/index');
        if (!in_array($data['c'].'/'.$data['a'], $arr)) {
            db('admin_log')->insert($data);
        } 
    }


    /**
     * 处理json
     */
    protected function _ajaxPost($url,$post_data) {
        $res = request_post($url, $post_data);
        $firstChar = substr($res,0,1);
        if ($firstChar =='?') {
            $res = substr($res,2);
            $res = substr($res,0,strlen($res)-1);
        } elseif($firstChar == '(') {
            $res = substr($res,1);
            $res = substr($res,0,strlen($res)-1);
        }
        return json_decode($res,true);
    }

    /**
     * 处理json
     */
    protected function _ajaxLivePost($action,$post_data) {
        $url = config('api.live_api_url').'/'.$action;
        $res = request_post($url, $post_data);
        $firstChar = substr($res,0,1);
        if ($firstChar =='?') {
            $res = substr($res,2);
            $res = substr($res,0,strlen($res)-1);
        } elseif($firstChar == '(') {
            $res = substr($res,1);
            $res = substr($res,0,strlen($res)-1);
        }
        return json_decode($res,true);
    }

    //获取平台数据
    public function getPlatformData()
    {
        $data = db('platform')->select();
        $platformArr = array();
        foreach($data as $v){
            $platformArr[] = $v['pl_name'];
        }
        //dump($platformArr);
        return $platformArr;
    }


    function aliyun($savePath,$category='',$isunlink=false,$bucket="dddgame"){
        $accessKeyId = config('aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
        $accessKeySecret = config('aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
        $endpoint = config('aliyun_oss.endpoint');//你的阿里云OSS地址
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //        判断bucketname是否存在，不存在就去创建
        if( !$ossClient->doesBucketExist($bucket)){
            $ossClient->createBucket($bucket);
        }
        $category=empty($category)?$bucket:$category;

        $savePath = str_replace("\\","/",$savePath);

        $object = $category.'/'.$savePath;//想要保存文件的名称
        $file = './uploads/'.$savePath;//文件路径，必须是本地的。

        try{
            $ossClient->uploadFile($bucket,$object,$file);
            if ($isunlink==true){
                unlink($file);
            }
        }catch (OssException $e){
            $e->getErrorMessage();
        }
        $oss=config('aliyun_oss.url');
        return $oss."/".$object;
    }

    public function qiniuyun($savePath)
    {
        require '../vendor/qiniu/autoload.php';
        // 用于签名的公钥和私钥
        $accessKey = 'CUhQeGgviWj_rtObYlo5qgGuJOUmR1A3Tpb0YAgH';
        $secretKey = 'Zl5WFzeOUy26OQlyzU3yfriZCGYJoRe2UxWggGzV';
        // 初始化签权对象
        $auth = new Auth($accessKey, $secretKey);
        //空间名
        $bucket = 'yunlutong-123';
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = 'uploads/'.$savePath;
        // 上传到七牛后保存的文件名
        $key = 'ylt-'.$filePath;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            $this->error($err);
        } else {
            $key = str_replace('\\', '%5C', $ret['key']);
            return 'http://oybi6sp1j.bkt.clouddn.com/'.$key;
        }
    }

    //文件下载
    protected  function fileDownLoad($file){
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }
    }

}
